<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\User;
use app\admin\model\PayConfig;
use app\admin\model\ProductMessage;
use app\admin\model\Configuration;
use app\admin\model\Payment;
use app\admin\model\Shop;
use app\admin\model\ShopOrder;
use app\admin\model\ShopPriceLog;
use app\admin\model\BalanceOrder;
use app\admin\model\Product;
use app\admin\model\UserRoseLog;
use app\admin\model\MpType;
use app\admin\model\UserOrder;
use getui\GeTui;
use addons\shopro\library\AdapayService;
use think\Db;
use think\Log;
use think\Exception;
use think\Session;

class Pay extends Api
{
	protected $noNeedLogin = ['notifyx','dy_notifyx','dy_notifyx_refund','dy_return_pay'];
	protected $appid;
	protected $secret;

	public function _initialize(){
		$action = request()->action();
		$ignore = array('host','accept','content-length','content-type');
		$headers = array();
		if($this->request->request('token')){
			$headers['token'] = $this->request->request('token');
		}else{
			foreach($_SERVER as $key=>$value){
				if(substr($key, 0, 5)==='HTTP_'){
					$key = substr($key, 5);
					$key = str_replace('_', ' ', $key);
					$key = str_replace(' ', '-', $key);
					$key = strtolower($key);
					if(!in_array($key, $ignore)){
						$headers[$key] = $value;
					}
				}
			}
		}
		if(empty($headers['token']) && in_array($action,$this->noNeedLogin)){
			//当未传token并且控制器可不不传token情况下不需要验证登录
		}else{
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=User::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
            if($this->user['status'] != 1){
                $this->error('账号异常');
            }
			User::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}
		
        $info = PayConfig::where(['name'=>'wechat'])->find();
        if($info){
            $val = json_decode($info['value'],true);
            $this->appid = $val['app_id'];
            $this->secret = $val['secret'];
        }
	}

    //查看是否支付
    public function estimate(){
        $id = $this->request->request('id','');
        $info = MpType::where(['id'=>$id])->find();
        if(!$info){
            $this->error('参数错误');
        }
        $data = [
            'user_id'=>$this->user['id'],
            'mp_type_id'=>$id,
            'price'=>$info['price'],
            'status'=>2
        ];
        $res = UserOrder::where($data)->find();
        if($res){
            $this->success('操作成功',$res['id']);
        }else{
            $this->error('操作失败');
        }
    }

    //创建预支付订单
    public function create_order(){
        $use_num = $this->request->request('num','');
        if(!$use_num){
            $this->error('参数错误');
        }
        if($use_num == 1){
            $price = 1;
        }elseif($use_num == 5){
            $price = 45;
        }elseif($use_num == 10){
            $price = 80;
        }elseif($use_num == 30){
            $price = 220;
        }elseif($use_num == 50){
            $price = 300;
        }elseif($use_num == 10000000){
            $price = 688;
        }else{
            $this->error('参数错误');
        }

        $data = [
            'user_id'=>$this->user['id'],
            'order_id'=>date("YmdHis").rand(1000,9999),
            'price'=>$price,
            'add_time'=>time(),
            'use_num'=>$use_num
        ];
        $id = UserOrder::insertGetId($data);
        $this->success('操作成功',['id'=>$id,'order_id'=>$data['order_id'],'price'=>$price]);
    }
    
     /**
     * 拉起支付
     */
    public function prepay(){
        $order_id = $this->request->post('order_id');
        $payment = $this->request->post('payment');
        $openid = $this->request->post('openid', '');
        $price = $this->request->post('price', '');
        $code = $this->request->post('code', '');
        $platform = $this->request->post('platform', 'wxMiniProgram');
        if ($platform == 'wxMiniProgram' && !$openid && $code) $openid = $this->LightOpenID($code);
        $order = UserOrder::where('id', $order_id)->find();
        if (!$order)  {$this->error("订单不存在");}
        $order_data = [
            'out_trade_no' => $order['order_id'],
            'total_fee' => $price,
        ];
        if($payment == 'wechat') {// 微信公众号，小程序支付，必须有 openid
            if (in_array($platform, ['wxOfficialAccount', 'wxMiniProgram'])) {
                $order_data['openid'] = $openid;
                if (empty($order_data['openid'])) {
                    return $this->success('缺少 openid', 'no_openid');
                }
            }
            $order_data['body'] = '会员充值';
        }
        $notify_url = $this->request->root(true) . '/api/pay/notifyx/payment/' . $payment . '/platform/product';
        $pay = new PayService($payment,$platform, $notify_url);
        try {
            $result = $pay->create($order_data);
        } catch (\Yansongda\Pay\Exceptions\Exception $e) {
            $this->error("支付配置错误：" . $e->getMessage());
        }
        if ($platform == 'App') {
            $result = $result->getContent();
        }
        $row = [
            'type'=>'pay',
            'pay_type'=>$payment,
            'order_id'=>$order['id'],
            'out_trade_no'=>$order['order_id'],
            'createtime'=>time(),
            'amount'=>$price,
            'pay_amount'=>0,
            'status'=>'loading',
            'pay_json'=>'',
            'payment_id'=>'',
            'transaction_id'=>'',
            'pay_time'=>0,
            'user_id'=>$order['user_id'],
            'platform'=>$platform,
            'use_type'=>'order',
        ];
        Payment::create($row);
        $pay_method = [
            'wechat'=>'wechat',
            'alipay'=>'alipay',
            'adapay_wechat'=>'wechat',
            'adapay_alipay'=>'alipay',
            'wallet'=>'wallet',
        ];

        $this->success('获取预付款成功', [
            'pay_data' => $result,
            'pay_action' => $pay_method[$payment],
        ]);
    }
    /**
     * 支付成功回调
     * @return mixed
     */
    public function notifyx()
    {
        $payment = $this->request->param('payment');
        $platform = $this->request->param('platform');
        $pay = new PayService($payment, $platform);
        $result = $pay->notify(function ($data, $pay) use ($payment, $platform) {
            /* {    // 微信回调参数
                "appid":"wx39cd0799d4567dd0",
                "bank_type":"OTHERS",
                "cash_fee":"1",
                "fee_type":"CNY",
                "is_subscribe":"N",
                "mch_id":"1481069012",
                "nonce_str":"dPpcZ6AzCDU8daNC",
                "openid":"oD9ko4x7QMDQPZEuN8V5jtZjie3g",
                "out_trade_no":"202010240834057843002700",
                "result_code":"SUCCESS",
                "return_code":"SUCCESS",
                "sign":"3103B6D06F13D2B3959C5B3F7F1FD61C",
                "time_end":"20200407102424",
                "total_fee":"1",
                "trade_type":"JSAPI",
                "transaction_id":"4200000479202004070804485027"
            } */
            /*  {    // 支付宝支付成功回调参数
                "gmt_create":"2020-04-10 19:15:00",
                "charset":"utf-8",
                "seller_email":"xptech@qq.com",
                "subject":"\u5546\u57ce\u8ba2\u5355\u652f\u4ed8",
                "sign":"AOiYZ1a2mEMOuIbHFCi6V6A0LJ97UMiHsCWgNdSU9dlzKFl15Ts8b0mL\/tN+Hhskl+94S3OUiNTBD3dD0Kv923SqaTWxNdj533PCdo2GDKsZIZgKbavnOvaccSKUdmQRE9KtmePPq9V9lFzEQvdUkKq1M8KAWO5K9LTy2iT2y5CUynpiu\/04GVzsTL9PqY+LDwqj6K+w7MgceWm1BWaFWg27AXIRw7wvsFckr3k9GGajgE2fufhoCYGYtGFbhGOp6ExtqS5RXBuPODOyRhBLpD8mwpOX38Oy0X+R4YQIrOi02dhqwPpvw79YjnvgXY3qZEQ66EdUsrT7EBdcPHK0Gw==",
                "buyer_id":"2088902485164146",
                "invoice_amount":"0.01",
                "notify_id":"2020041000222191501064141414240102",
                "fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"PCREDIT\"}]",
                "notify_type":"trade_status_sync",
                "trade_status":"TRADE_SUCCESS",
                "receipt_amount":"0.01",
                "buyer_pay_amount":"0.01",
                "app_id":"2021001114666742",
                "sign_type":"RSA2",
                "seller_id":"2088721922277739",
                "gmt_payment":"2020-04-10 19:15:00",
                "notify_time":"2020-04-10 19:15:01",
                "version":"1.0",
                "out_trade_no":"202007144778322770017000",
                "total_amount":"0.01",
                "trade_no":"2020041022001464141443020240",
                "auth_app_id":"2021001114666742",
                "buyer_logon_id":"157***@163.com",
                "point_amount":"0.00"
            } */
            /* {   // 支付宝退款成功（交易关闭）回调参数
                "gmt_create": "2020-08-15 14:48:32",
                "charset": "utf-8",
                "seller_email": "xptech@qq.com",
                "gmt_payment": "2020-08-15 14:48:32",
                "notify_time": "2020-08-15 16:11:45",
                "subject": "商城订单支付",
                "gmt_refund": "2020-08-15 16:11:45.140",
                "sign": "b6ArkgzLIRteRL9FMGC6i\/jf6VwFYQbaGDGRx002W+pdmN5q9+O4edZ3ALF74fYaijSl9ksNr0dKdvanu3uYxBTcd\/GIS4N1CWzmCOv6pzgx5rO\/YvGoHLM3Yop0GKKuMxmnNsZ6jhYKEY7SYD3Y0L6PU9ZMdHV7yIiVj+zZmbKzUgK9MPDCEXs+nzpNAiSM8GTqYRSUvKobAK68hswG2k1QIcqr5z+ZmVYa\/nHHkoC9qXt5zwyGi4P+2eOsr6V2PjA3x8qqe7TN5aI1DeoZD5KqHPYYaYF17J2q6YPlgl3WUl1RhE7H86bivB1fIuYEv\/3+JR74WN\/o7krGw1RPHg==",
                "out_biz_no": "R202004114414846255015300",
                "buyer_id": "2088902485164146",
                "version": "1.0",
                "notify_id": "2020081500222161145064141453349793",
                "notify_type": "trade_status_sync",
                "out_trade_no": "202002460317545607015300",
                "total_amount": "0.01",
                "trade_status": "TRADE_CLOSED",
                "refund_fee": "0.01",
                "trade_no": "2020081522001464141438570535",
                "auth_app_id": "2021001114666742",
                "buyer_logon_id": "157***@163.com",
                "gmt_close": "2020-08-15 16:11:45",
                "app_id": "2021001114666742",
                "sign_type": "RSA2",
                "seller_id": "2088721922277739"
            } */
            //db('log')->insert(['text'=>json_encode($data)]);
            //$data = json_decode('{"appid":"wx84f56a63b9f63e03","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1650562174","nonce_str":"ZhHilq8KWIjf1EBv","openid":"o_sKy5N0XBUBqa5hrSHRxqfIq5J4","out_trade_no":"202309071029199121","result_code":"SUCCESS","return_code":"SUCCESS","sign":"492D1BBAA4B9263D080C9D40254CE8FA","time_end":"20230907102930","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200001944202309072304948815"}',true);
            try {
                $out_trade_no = $data['out_trade_no'];
                $out_refund_no = $data['out_biz_no'] ?? '';
                // 判断支付宝微信是否是支付成功状态，如果不是，直接返回响应
                if ($payment == 'alipay' && $data['trade_status'] != 'TRADE_SUCCESS') {
                    // 不是交易成功的通知，直接返回成功
                    return $pay->success()->send();
                }
                if ($payment == 'wechat' && ($data['result_code'] != 'SUCCESS' || $data['return_code'] != 'SUCCESS')) {
                    // 微信交易未成功，返回 false，让微信再次通知
                    return false;
                }
                // 支付成功流程
                $pay_fee = $payment == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                $paymentinfo = Payment::get(['out_trade_no'=>$out_trade_no]);
                //你可以在此编写订单逻辑
                if($platform == 'product'){
                    $order = UserOrder::where('order_id', $out_trade_no)->find();
                    if (!$order || $order->status != 1) {
                        // 订单不存在，或者订单已支付
                        return $pay->success()->send();
                    }
                    //订单支付完成时同步支付流水状态
                    $this->syncPaymentInfo($out_trade_no, $data, $paymentinfo);
                
                    $notify = [
                        'order_sn' => $data['out_trade_no'],
                        'transaction_id' => $payment == 'alipay' ? $data['trade_no'] : $data['transaction_id'],
                        'notify_time' => date('Y-m-d H:i:s', strtotime($data['time_end'])),
                        'buyer_email' => $order->user_id,
                        'payment_json' => json_encode($data),
                        'pay_fee' => $pay_fee,
                        'pay_type' => $payment// 支付方式
                    ];
                    $this->paymentProcess($order, $notify);
                }
                
                return $pay->success()->send();
           } catch (\Exception $e) {
            }
       });

        return $result;
    }
    //更新订单状态
    private function paymentProcess($order, $notify) {

        $order->status = 2;
        $order->paytime = time();
        $order->transaction_id = $notify['transaction_id'];
        $order->payment_json = $notify['payment_json'];
        $order->pay_type = $notify['pay_type'];
        $order->pay_fee = $notify['pay_fee'];
        $order->save();

        $user = User::where(['id'=>$order['user_id']])->find();
        User::where(['id'=>$order['user_id']])->update(['use_num'=>$order['use_num']+$user['use_num']]);

        /* //记录订单操作日志
        $oper_id = empty($oper) ? 0 : (is_array($oper) ? $oper['id'] : $oper->id);
        $self = new OrderAction();
        $self->order_id = $order['id'];
        $self->order_item_id = is_null($order) ? 0 : $order['id'];
        $self->oper_type = 'user';
        $self->oper_id = $oper_id;
        $self->order_status = is_null($order) ? 0 : $order['status'];
        $self->dispatch_status = is_null($order) ? 0 : $order['dispatch_status'];
        $self->comment_status = is_null($order) ? 0 : $order['comment_status'];
        $self->aftersale_status = is_null($order) ? 0 : $order['aftersale_status'];
        $self->refund_status = is_null($order) ? 0 : $order['refund_status'];
        $self->remark = '用户支付成功';
        $self->save(); */
    }

    
	//下单成功后操作
	private function sendOrderSuccess($data,$product){
		
        if($product['type_status'] < 3){ //积分购买
            roseandlog($data['user_id'],0-$data['total_money'],5,'兑换商品扣除');
        }
       

		ProductMessage::insert(array('product_id'=>$data['product_id'],'message_id'=>0,'title'=>'买家'.User::where('id',$data['user_id'])->value('nickname').'下单了，请尽快发货:【'.$product['title'].'】','user_id'=>$data['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
		$configuration=Configuration::where(array('id'=>1))->find();
		// 注意使用GMT时间  
		date_default_timezone_set("GMT");  
		$target = "https://dysmsapi.aliyuncs.com/?";  
		$dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范  
		$accessKeyId = $configuration['access_key'];      // 这里填写您的Access Key ID  
		$accessKeySecret = $configuration['access_secret'];  // 这里填写您的Access Key Secret  
		$ParamString="{}";
		$mobile=$product['phone'];
        if($product['type_status'] < 3){
            //判断是正常闲置还是排队闲置
            if($data['paidui'] == 1){
                $TemplateCode = 'SMS_472070160';
            }else{
                $TemplateCode = 'SMS_274540075';
            }
        }else{
            $TemplateCode = 'SMS_469060207';
        }

		$data_info = array(  
			'AccessKeyId' => $accessKeyId,
			'Action' => 'SendSms',
			'Format' => 'XML', 
			'OutId' => '123',
			'PhoneNumbers' => $mobile,
			'RegionId' => 'cn-hangzhou',
			'SignName'=>$configuration['sign_name'],
			'SignatureMethod' => 'HMAC-SHA1',
			'SignatureNonce'=> '45e25e9b-0a6f-4070-8c85-'.uniqid(),
			'SignatureVersion' => '1.0',
			'TemplateCode' => $TemplateCode, 
			'TemplateParam' => $ParamString,
			'Timestamp' => date("Y-m-d H:i:s"), 
			'Version' => '2017-05-25'
		);  
		$data_info['Signature'] = computeSignature($data_info, $accessKeySecret);  
		// 发送请求  
		$result = xml_to_array(https_request($target.http_build_query($data_info)));
		//print_r($result);
		if(!empty($result['Error']['Message'])){
			$this->error($result['Error']['Message']);
		}

        if($product['notice'] == 0){
			return true;
		}
        if($product['type_status'] < 3){ //积分购买
            if($data['paidui'] == 1){
                $thing4 = '你的闲置有人参与排队了，快去看看吧！';
            }else{
                $thing4 = '你的闲置已赠出，请去订单页进行预约取件！';
            }
        }else{
            $thing4 = '你的闲置已出售，请及时去预约快递确认发货！';
        }
        //发送订阅消息
		$data = [
			"thing8"=>["value"=>$product['title']],
            "thing3"=>[ "value"=> '待发货'], 
            "thing4"=>["value"=>$thing4 ]
		];
		send_subscription($product['user_id'],'UJnRdmFH3FHRqisFtbKCuYJRxHEK1J8sJydn0DToLFg','/pages/user/sellOrder',$data);
	}
    
    /**
     * 同步支付流水的结果
     * @param $out_trade_no
     * @param $data
     * @param $payment
     * @return void
     * @throws \think\exception\DbException
     */
    private function syncPaymentInfo($out_trade_no, $data, $payment) {
        $paymentinfo = Payment::get(['out_trade_no'=>$out_trade_no]);

        $pay_fee = $payment == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;

        $paymentinfo['updatetime'] = time();
        $paymentinfo['pay_amount'] = $pay_fee;
        $paymentinfo['status'] = 'success';
        $paymentinfo['pay_json'] = json_encode($data, JSON_UNESCAPED_UNICODE);
        $paymentinfo['transaction_id'] = $payment == 'alipay' ? $data['trade_no'] : $data['transaction_id'];
        $paymentinfo['pay_time'] = time();
        $paymentinfo->save();
    }

  
    /**
     * 获取用户openid
     * @param $code
     * @return mixed|void
     */
    public function LightOpenID($code) {

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->appid.'&secret='.$this->secret.'&js_code='.$code.'&grant_type=authorization_code';
        
        $result = file_get_contents($url);
        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            $this->error('获取openid时异常，微信内部错误');
        } else {
            if (array_key_exists('errcode', $wxResult)) {
                $this->error($result);
            } else {
                return $openid = $wxResult['openid'];
            }
        }
    }



    /**
     * 订单执行退款
     * @param $order  订单数据
     * @param $refund_money  退款金额
     * @return void
     * @throws \think\exception\DbException
     */
    public static function doOrderRefund($order, $refund_money, $nickname,$arr) {
       
        Db::startTrans();
		try {
            $paymentinfo = Payment::get(['out_trade_no'=>$order['order_id']]);
            if(!$paymentinfo){
                //未查询到退款订单数据
                $arr['text'] = '未查询到退款订单数据';
                db('order_log')->insert($arr);
                return true;
            }
            $out_refund_no = date("YmdHis".$order['id']);
            switch ($order['pay_type']) {
                case 'wechat':
                    $refund_data = [
                        'out_trade_no'=>$order['order_id'],
                        'out_refund_no'=>$out_refund_no,
                        'total_fee'=>$order['pay_fee']*100,
                        'refund_fee'=>$refund_money*100,
                    ];
                    break;
                case 'alipay':
                    $refund_data = [
                        'out_trade_no'=>$order->order_sn,
                        'refund_amount'=>$order->pay_fee,
                    ];
                    break;
                default:
                    $arr['text'] = '错误的支付方式';
                    db('order_log')->insert($arr);
                    Db::rollback();
                    throw new \Exception('错误的支付方式');
                    break;
            }

            $pay = new PayService($order['pay_type'], $paymentinfo['platform']);
            $result = $pay->refund($refund_data);

            if((isset($result['return_code'])&&$result['return_code']=='SUCCESS')||(isset($result['trans_state'])&&$result['trans_state']=='S')){
                //添加退款记录
                $row = [
                    'type'=>'refund',
                    'pay_type'=>$order->pay_type,
                    'order_id'=>$order->id,
                    'out_trade_no'=>$paymentinfo['out_trade_no'],
                    'createtime'=>time(),
                    'updatetime'=>time(),
                    'pay_time'=>time(),
                    'amount'=>$refund_money,
                    'pay_amount'=>$refund_money,
                    'status'=>'success',
                    'pay_json'=>json_encode($result, JSON_UNESCAPED_UNICODE),
                    'payment_id'=>$out_refund_no,
                    'transaction_id'=>$result['transaction_id']??$result['payment_id'],
                    'refund_id'=>$result['refund_id']??$result['id'],
                    'user_id'=>$order->user_id,
                    'platform'=>$paymentinfo->platform,
                    'use_type'=>'order',
                ];
                Payment::insert($row);

                //退款成功后操作逻辑
                if($order['is_shopping'] == 0){
                    //不是商城订单则退回积分
                    roseandlog($order['user_id'],$order['total_money'],18,'取消订单，退回');
                }
                $product=Product::where(array('id'=>$order['product_id']))->find();
                ProductMessage::insert(array('product_id'=>$order['product_id'],'title'=>'买家'.$nickname.'取消订单，取消发货:【'.$product['title'].'】','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                Product::where(array('id'=>$order['product_id']))->update(array('is_sale'=>0));

                UserOrder::where(['id'=>$order['id']])->update(['status'=>-1,'paidui'=>0,'paidui_content'=>'']);

                $arr['text'] = '退款成功';
                db('order_log')->insert($arr);
            }else{
                $arr['text'] = '退款失败';
                db('order_log')->insert($arr);
                throw new \Exception('退款失败');
            }
            Db::commit();
		} catch (Exception $e) {
			Db::rollback();
            throw new \Exception('退款失败');
		}
        
        
    }



    /**
     * 支付下单
     * 服务端预下单
     * @param $data
     */
    public function dy_pay()
    {
        $order_id = $this->request->request('order_id','');
        $data = UserOrder::where(['id'=>$order_id])->find();
        if(!$data){
            $this->error('参数错误');
        }
        $url = 'https://developer.toutiao.com/api/apps/ecpay/v1/create_order';
        $postdata['app_id'] = 'tt414337fede7516a001';
        $postdata['out_order_no'] = $data['order_id'];//订单号
        $postdata['total_amount'] = intval($data['price']*100);//支付金额
        $postdata['subject'] = '会员充值';
        $postdata['body'] = '会员充值';//备注
        $postdata['valid_time'] = 86400;//订单有效时间
        $postdata['cp_extra'] = $order_id;
        $postdata['notify_url'] = 'https://mp.yuxiang123.cn/api/pay/dy_notifyx';
        $postdata['thirdparty_id'] = '';
        $postdata['disable_msg'] = 0;
        $postdata['msg_page'] = 'asger';
        $postdata['store_uid'] = '1';
        $postdata['sign'] = $this->sign($postdata);//获取签名
        $res = $this->json_post($url, $postdata);
 
        if($res['err_no'] == 0 && $res['err_tips'] == 'success'){
            $this->success('操作成功',$res);
        }else{
            $this->error('参数错误');
        }
    }


     /**
     * 抖音支付退款
     * 服务端预退款
     * @param $data
     */
    public function dy_return_pay()
    {
        $order_id = $this->request->request('order_id','');
        $data = UserOrder::where(['id'=>$order_id])->find();
        if(!$data){
            $this->error('参数错误');
        }
        $url = 'https://developer.toutiao.com/api/apps/ecpay/v1/create_refund';
        $postdata['app_id'] = 'tt414337fede7516a001';
        $postdata['out_order_no'] = $data['order_id'];//订单号
        $postdata['out_refund_no'] = $data['transaction_id'];
        $postdata['reason'] = '发错地址';
        $postdata['refund_amount'] = intval($data['price']*100);//退款金额
        $postdata['sign'] = $this->sign($postdata);//获取签名
        $res = $this->json_post($url, $postdata);
        dd($res);
        if($res['err_no'] == 0 && $res['err_tips'] == 'success'){
            $this->success('操作成功',$res);
        }else{
            $this->error('参数错误');
        }
    }

    function sign($map) {
        $rList = array();
        foreach($map as $k =>$v) {
            if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id")
                continue;
            $value = trim(strval($v));
            $len = strlen($value);
            if ($len > 1 && substr($value, 0,1)=="\"" && substr($value,$len, $len-1)=="\"")
                $value = substr($value,1, $len-1);
            $value = trim($value);
            if ($value == "" || $value == "null")
                continue;
            array_push($rList, $value);
        }
        array_push($rList, "KSXZbnCizuYtm3znt3mUE4QFNcPjEWWkroOIPDGM");
        sort($rList, 2);
        return md5(implode('&', $rList));
    }

    function json_post($url, $data = NULL)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            return 'data is null';
        }
        if (is_array($data)) {
            $data = json_encode($data,320);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);

        return json_decode($res,true) ;
    }

    /**
     * 支付成功回调
     * @return mixed
     */
    public function dy_notifyx()
    {
        $res = input();
        $res['msg'] = str_replace('&quot;', '"', $res['msg']);
        $data = json_decode( $res['msg'],true);
        db('log')->insert(['text'=>json_encode($res),'add_time'=>date('Y-m-d H:i:s'),'type'=>'抖音订单回调','order_id'=>$data['cp_extra']]);
        if($res['type'] == 'refund' && $data['status'] == 'SUCCESS'){
            return json(['err_no'=>0,'err_tips'=>'success']);
        }
        if($data['status'] == 'SUCCESS' ){ //支付成功
            Db::startTrans();
            try {
                $order = UserOrder::where(['order_id'=>$data['cp_orderno'],'status'=>1])->find();
                if(!$order){
                    return json(['err_no'=>0,'err_tips'=>'success']);
                }
                //支付成功更新订单状态
                $arr = [
                    'pay_type'=>'dy',
                    'paytime'=>time(),
                    'transaction_id'=>$data['payment_order_no'],
                    'payment_json'=>json_encode($data),
                    'pay_fee'=>$data['total_amount']/100,
                    'status'=>2
                ];
                UserOrder::where(['id'=>$order['id']])->update($arr);
                $user = User::where(['id'=>$order['user_id']])->find();
                User::where(['id'=>$order['user_id']])->update(['use_num'=>$order['use_num']+$user['use_num']]);

                Db::commit();
                return json(['err_no'=>0,'err_tips'=>'success']);
            } catch (\Exception $e) {
                Db::rollback();
                db('log')->insert(['text'=>$e->getMessage(),'add_time'=>date('Y-m-d H:i:s'),'type'=>'抖音订单回调','order_id'=>$data['cp_extra']]);
                return json(['err_no'=>400,'err_tips'=>'business fail']);
            }
        }
    }
}